import { User } from '../model/user'
import { IamUtil } from '../utils/iamUtil'
const constants = {
  SUCCESS: 'success',
  FAILED: 'failed',
  TRUE_BOOLEAN: true,
  FALSE_BOOLEAN: false
}
export class LoginDao {
  checkEmail(params: any): Promise<boolean> {
    return User.findAll({ where: { account: params.email } }).then((data: any) => {
      if (data.length === 0) {
        return constants.TRUE_BOOLEAN
      } else if (data.length > 0) {
        return constants.FALSE_BOOLEAN
      }
    })
  }
  register(params: any): Promise<boolean> {
    return User
      .findOrCreate({ where: { account: params.account }, defaults: params })
      .then((result: any) => {
        if (result[1]) {
          return constants.TRUE_BOOLEAN
        } else {
          return constants.FALSE_BOOLEAN
        }
      })
  }
  login(params: any): Promise<string> {
    return User
      .findAll({ where: { account: params.account, password: params.password } })
      .then((data: Array<User>) => {
        if (data.length === 0) {
          return null
        } else {
          return IamUtil.createToken(params.account)
        }
      })
  }
  verifyLogin(params: any): Promise<string> {
    return new Promise((resolve, reject) => {
      IamUtil.verifyToken(params.token, (result: string) => {
        resolve(result)
      })
    })
  }
}
